/**
 * Truffle Search
 * by bowlofnoodles
 */


package com.bowlofnoodles.truffleclient;

import com.google.android.c2dm.C2DMessaging;
import com.lukencode.android.RestClient;

import android.accounts.Account;
import android.accounts.AccountManager;
import android.app.Activity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;
import android.widget.Button;

public class MainView extends Activity {
	
	protected AccountManager accountManager;	
	protected Account[] accounts;
	protected String[] accountNames;
	private Spinner s;
	
	private boolean searchingNow;
	
	//private static final String SERVER_URL = "http://10.0.2.2:8888/trufflesearch";
	private static final String SERVER_URL = "http://trufflesearch.appspot.com/trufflesearch";
	
    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        
    	super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        
        s = (Spinner) findViewById(R.id.spinner1);
        
        // populate with all google accounts on the device
        accountManager = AccountManager.get(getApplicationContext());
        accounts = accountManager.getAccountsByType("com.google");
        String[] accountNames = new String[accounts.length];
        for (int i=0; i<accounts.length; i++) {
        	accountNames[i] = accounts[i].name;
        }
        
        ArrayAdapter<String> sArrAdd = 
        	new ArrayAdapter<String>(this, android.R.layout.simple_spinner_dropdown_item, accountNames);
        
        s.setAdapter(sArrAdd);
    }
    
    @Override
    public void onResume() {
    	super.onResume();
    	
    	// are we searching?
    	s = (Spinner) findViewById(R.id.spinner1);
    	if (s==null) return;
    	Object currentUser = s.getSelectedItem();
    	if (currentUser == null) return;
    	RestClient client = new RestClient(SERVER_URL);
    	client.AddParam("action", "getInfo");
    	client.AddParam("userAccount", currentUser.toString());
    	client.AddParam("parameter", "searchingNow");
    	try { client.Execute(RestClient.RequestMethod.POST); }
    	catch (Exception e) { e.printStackTrace(); }
    	
    	String resp = client.getResponse();
    	//Log.e("TrufflesResp", resp);
    	
    	// GAE datastore doesn't guarantee a type returned - 
    	// just be safe and infer it from String data
    	searchingNow = resp.contains("true")?true:false;
    	
    	//debug
    	//Log.e("Trufflesverif", searchingNow?"true":"false");
    	
    	// draw the correct text on the button
    	Button b = (Button)findViewById(R.id.button3);
    	if (searchingNow) {
        	b.setText(R.string.stopsearch);
    	} else {
    		b.setText(R.string.searchsearch);
    	}
    	
    	// TODO: update grams found via some other event listener so that refreshing 
    	// this activity is not necessary to see the updated grams found
    	
    	// write grams found
    	client.ClearParams();
    	client.AddParam("action", "getInfo");
    	client.AddParam("userAccount", s.getSelectedItem().toString());
    	client.AddParam("parameter", "gramsFound");
    	try { client.Execute(RestClient.RequestMethod.POST); }
    	catch (Exception e) { e.printStackTrace(); 	}
    	resp = client.getResponse();
    	TextView t = (TextView)findViewById(R.id.gramsFoundText);
    	t.setText((resp!=null?resp.replaceAll("[\n\r]", ""):"Unavailable ") + "g");
    	
    }
    	
    /**
     * This function is called when the Search button is pressed.
     * It registers the user if the id is not found in the database.
     * 
     * There is no security implemented at this point. The app just
     * matches on the google account name.
     * @param view
     */
    public void register(View view) {
    	
    	RestClient client = new RestClient(SERVER_URL);
    	
    	if (searchingNow) {
    		
    		// stop search
    		C2DMessaging.unregister(this);
    		client.ClearParams();
    		client.AddParam("userAccount", s.getSelectedItem().toString());
    		client.AddParam("action", "setInfo");
    		client.AddParam("parameter", "searchingNow");
    		client.AddParam("value", "false");
    		
    		// update database
    		try { client.Execute(RestClient.RequestMethod.POST); }
        	catch (Exception e) { e.printStackTrace(); }
    		
        	// change button text
        	Button b = (Button)findViewById(R.id.button3);
    		b.setText(R.string.searchsearch);
    		Toast.makeText(getApplicationContext(), R.string.bringpigs, Toast.LENGTH_SHORT).show();
    		searchingNow = false;
    		return;
    	}
    	
    	// try login
    	client.ClearParams();
    	client.AddParam("action", "doLogin");
    	client.AddParam("userAccount", s.getSelectedItem().toString());
    	try { client.Execute(RestClient.RequestMethod.POST); }
    	catch (Exception e) { e.printStackTrace(); }
    	
    	String resp = client.getResponse();
    	if (resp == null) { Log.e("Truffles", "no response from server"); return; }
    	
    	// debug info (visible in android LogCat)
    	Log.e("C2DM", resp);
    	
    	if (resp.contains("hajimemashite")) {
    		// update datastore record with c2dm reg_id
    		
    		C2DMessaging.register(this, "149258@gmail.com");
    		String reg_id = C2DMessaging.getRegistrationId(getApplicationContext()); 
    		if (reg_id==null) {
    			Log.e("C2DM", "failed to register device with C2DM");
    			return;
    		}
    		
    		// store device id in database
    		client.ClearParams();
    		client.AddParam("action", "doRegister");
    		client.AddParam("userAccount", s.getSelectedItem().toString());
    		client.AddParam("c2dm_reg_id", reg_id);
    		try {client.Execute(RestClient.RequestMethod.POST); }
    		catch (Exception e) { e.printStackTrace(); }
    	}
    	
		Toast.makeText(getApplicationContext(), R.string.sendpigs, Toast.LENGTH_SHORT).show();
		searchingNow = true;
		
		// update database
		client.ClearParams();
		client.AddParam("userAccount", s.getSelectedItem().toString());
		client.AddParam("action", "setInfo");
		client.AddParam("parameter", "searchingNow");
		client.AddParam("value", "true");
		try { client.Execute(RestClient.RequestMethod.POST); }
    	catch (Exception e) { e.printStackTrace(); }
		
    	Button b = (Button)findViewById(R.id.button3);
		b.setText(R.string.stopsearch);
	
    }
    
    /**
     * Called when the search is stopped. The device will stop receiving notifications
     * until the search is restarted.
     * @param view
     */
    public void unregister(View view) {
    	C2DMessaging.unregister(this);
    }

}